package com.huixh.train.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huixh.train.business.domain.TrainCarriage;
import com.huixh.train.business.enums.SeatColEnum;
import com.huixh.train.business.service.TrainCarriageService;
import com.huixh.train.common.resp.PageResult;
import com.huixh.train.business.domain.TrainSeat;
import com.huixh.train.business.domain.TrainSeatExample;
import com.huixh.train.business.mapper.TrainSeatMapper;
import com.huixh.train.business.req.TrainSeatQueryReq;
import com.huixh.train.business.req.TrainSeatSaveReq;
import com.huixh.train.business.resp.TrainSeatQueryResp;
import com.huixh.train.business.service.TrainSeatService;
import com.huixh.train.utils.random.SnowUtil;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author huixh
 */
@Service
public class TrainSeatServiceImpl implements TrainSeatService {

    private final Logger logger = LoggerFactory.getLogger(TrainSeatServiceImpl.class);
    @Resource
    private TrainSeatMapper trainSeatMapper;
    @Resource
    private TrainCarriageService trainCarriageService;

    @Resource
    private SnowUtil snowUtil;

    @Override
    public void save(TrainSeatSaveReq trainSeatSaveReq) {
        DateTime now = DateTime.now();
        TrainSeat trainSeat = BeanUtil.copyProperties(trainSeatSaveReq, TrainSeat.class);
        if (ObjectUtil.isNull(trainSeat.getId())) {
            trainSeat.setId(snowUtil.getSnowflakeToLong());
            trainSeat.setCreateTime(now);
            trainSeat.setUpdateTime(now);
            trainSeatMapper.insert(trainSeat);
        } else {
            trainSeat.setUpdateTime(now);
            trainSeatMapper.updateByPrimaryKey(trainSeat);
        }
    }

    @Override
    public PageResult<List<TrainSeatQueryResp>> queryList(TrainSeatQueryReq trainSeatQueryReq) {
        TrainSeatExample trainSeatExample = new TrainSeatExample();
        trainSeatExample.setOrderByClause("train_code asc, carriage_index asc, carriage_seat_index asc");
        TrainSeatExample.Criteria criteria = trainSeatExample.createCriteria();

        if (StrUtil.isNotBlank(trainSeatQueryReq.getTrainCode())) {
            criteria.andTrainCodeEqualTo(trainSeatQueryReq.getTrainCode());
        }

        logger.info("查询页码：{}", trainSeatQueryReq.getPageNum());
        logger.info("每页条数：{}", trainSeatQueryReq.getPageSize());
        PageHelper.startPage(trainSeatQueryReq.getPageNum(), trainSeatQueryReq.getPageSize());
        List<TrainSeat> trainSeatList = trainSeatMapper.selectByExample(trainSeatExample);

        PageInfo<TrainSeat> pageInfo = new PageInfo<>(trainSeatList);
        logger.info("总行数：{}", pageInfo.getTotal());
        logger.info("总页数：{}", pageInfo.getPages());

        List<TrainSeatQueryResp> list = BeanUtil.copyToList(trainSeatList, TrainSeatQueryResp.class);
        return PageResult.success(pageInfo.getTotal(), list);
    }

    @Override
    public void delete(Long id) {
        trainSeatMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void genTrainSeat(String trainCode){
        DateTime now = DateTime.now();
        // 清空当前车下所有座位记录
        TrainSeatExample trainSeatExample = new TrainSeatExample();
        TrainSeatExample.Criteria criteria = trainSeatExample.createCriteria();
        criteria.andTrainCodeEqualTo(trainCode);
        trainSeatMapper.deleteByExample(trainSeatExample);
        // 查找当前车次下所有车厢
        List<TrainCarriage> trainCarriages = trainCarriageService.selectByTrainCode(trainCode);

        if (trainCarriages == null || trainCarriages.size() == 0) {
            return;
        }
        logger.info("当前车次车厢数：{}", trainCarriages.size());
        //循环生成车厢每个座位
        trainCarriages.forEach(trainCarriage -> {
            Integer rowCount = trainCarriage.getRowCount();
            String seatType = trainCarriage.getSeatType();
            int carriageSeatIndex = 1;
            List<SeatColEnum> seatColEnumList = SeatColEnum.getSeatColEnumList(seatType);
            logger.info("当前车厢：{}", trainCarriage.getIndex());
            for (int row = 1; row <= rowCount; row++) {
                for (SeatColEnum seatColEnum : seatColEnumList) {
                    TrainSeat trainSeat = new TrainSeat();
                    trainSeat.setId(snowUtil.getSnowflakeToLong());
                    trainSeat.setTrainCode(trainCode);
                    trainSeat.setCarriageIndex(trainCarriage.getIndex());
                    trainSeat.setRow(StrUtil.fillBefore(String.valueOf(row), '0', 2));
                    trainSeat.setCol(seatColEnum.getCode());
                    trainSeat.setSeatType(seatColEnum.getType());
                    trainSeat.setCarriageSeatIndex(carriageSeatIndex++);
                    trainSeat.setCreateTime(now);
                    trainSeat.setUpdateTime(now);
                    trainSeatMapper.insert(trainSeat);
                }
            }
        });
    }

    /**
     * 根据火车编码获取座位列表。
     *
     * @param trainCode 火车的编码，用于查询对应的座位信息。
     * @return 返回一个火车座位列表，列出了指定火车编码的所有可用座位。
     */
    @Override
    public List<TrainSeat> getSeatListByCode(String trainCode) {
        TrainSeatExample trainSeatExample = new TrainSeatExample();
        trainSeatExample.setOrderByClause("`id` asc");
        trainSeatExample.createCriteria().andTrainCodeEqualTo(trainCode);
        return trainSeatMapper.selectByExample(trainSeatExample);
    }
}